<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="registerRules"
    size="large"
  >
    <Motion>
      <el-form-item prop="username">
        <el-input
          v-model="ruleForm.username"
          clearable
          placeholder="用户名"
          :prefix-icon="useRenderIcon(User)"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="100">
      <el-form-item prop="password">
        <el-input
          v-model="ruleForm.password"
          clearable
          show-password
          placeholder="密码"
          :prefix-icon="useRenderIcon(Lock)"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="150">
      <el-form-item prop="repeatPassword">
        <el-input
          v-model="ruleForm.repeatPassword"
          clearable
          show-password
          placeholder="确认密码"
          :prefix-icon="useRenderIcon(Lock)"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="200">
      <el-form-item prop="nickname">
        <el-input
          v-model="ruleForm.nickname"
          clearable
          placeholder="昵称"
          :prefix-icon="useRenderIcon('ph:tag-fill')"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="250">
      <el-form-item prop="captcha">
        <el-input
          v-model="ruleForm.captcha"
          clearable
          placeholder="验证码"
          :prefix-icon="useRenderIcon('fluent:shield-keyhole-20-filled')"
        >
          <template v-slot:append>
            <ReImageVerify ref="refCaptcha" v-model:code="ruleForm.captchaId" />
          </template>
        </el-input>
      </el-form-item>
    </Motion>

    <Motion :delay="300">
      <el-form-item>
        <el-checkbox v-model="checked"> 我已仔细阅读并接受 </el-checkbox>
        <el-button link type="primary"> 《隐私政策》 </el-button>
      </el-form-item>
    </Motion>

    <Motion :delay="350">
      <el-form-item>
        <el-button
          class="w-full"
          size="default"
          type="primary"
          :loading="loading"
          @click="onRegiste(ruleFormRef)"
        >
          注册
        </el-button>
      </el-form-item>
    </Motion>

    <Motion :delay="400">
      <div class="text-right mt-4">
        已有账号?<span
          class="cursor-pointer text-blue-500 hover:text-blue-300"
          @click="emit('onBack', null)"
          >返回登录</span
        >
      </div>
    </Motion>
  </el-form>
</template>

<script setup lang="ts">
import { ReImageVerify } from '@/components/ReImageVerify'
import { ref, reactive } from 'vue'
import Motion from './utils/motion'
import { message } from '@/utils/message'
import type { FormInstance, FormRules } from 'element-plus'
import { useRenderIcon } from '@/components/ReIcon/src/hooks'
import Lock from '@iconify-icons/ri/lock-fill'
import User from '@iconify-icons/ri/user-3-fill'
import { registerUser } from '@/api/user'
import { HttpResultCode } from '@/utils/http/enums'

const refCaptcha = ref<InstanceType<typeof ReImageVerify>>()
const emit = defineEmits<{
  onBack: [{ username: string; password: string }]
}>()

const checked = ref(false)
const loading = ref(false)
const ruleForm = reactive({
  username: '',
  password: '',
  repeatPassword: '',
  nickname: '',
  captcha: '',
  captchaId: ''
})
const ruleFormRef = ref<FormInstance>()

const REGEXP_USERNAME = /^[a-zA-Z][a-zA-Z0-9_]{5,19}$/
const REGEXP_PWD = /^[a-zA-Z0-9][a-zA-Z0-9_]{5,19}$/
/** 注册校验 */
const registerRules = reactive<FormRules>({
  username: [
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('用户名不能为空'))
        } else if (!REGEXP_USERNAME.test(value)) {
          callback(
            new Error('用户名应为6-20位字母、数字、下划线的组合,且以字母开头')
          )
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else if (!REGEXP_PWD.test(value)) {
          callback(
            new Error(
              '密码应为6-20位字母、数字、下划线的组合,且以字母或数字开头'
            )
          )
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  repeatPassword: [
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入确认密码'))
        } else if (ruleForm.password !== value) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  nickname: [{ max: 20, message: '昵称最多20个字符', trigger: 'blur' }],
  captcha: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
})

const onRegiste = async (formEl: FormInstance | undefined) => {
  loading.value = true
  if (!formEl) return
  await formEl.validate(valid => {
    if (valid) {
      if (checked.value) {
        registerUser(ruleForm)
          .then(res => {
            if (res.code === HttpResultCode.Success) {
              message('注册成功', {
                type: 'success'
              })
              emit('onBack', ruleForm)
            } else {
              if (refCaptcha.value) {
                refCaptcha.value.getImgCode()
              }
              message(res.msg, { type: 'error' })
            }
          })
          .finally(() => {
            loading.value = false
          })
      } else {
        loading.value = false
        message('请先阅读并同意隐私政策', {
          type: 'warning'
        })
      }
    } else {
      loading.value = false
    }
  })
}
</script>
